import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import math
import webbrowser

class InsuranceCalculator:
    def __init__(self, root):

        self.root = root
        self.root.title("保险保费评估")
        self.root.geometry("900x580")
        self.root.resizable(True, True)
        self.root.configure(bg="#ffffff")

        self.colors = {
            "primary_red": "#DB0011",
            "secondary_red": "#E60028",
            "light_red": "#FFF0F0",
            "white": "#ffffff",
            "text": "#333333",
            "border": "#DB0011",
            "gray": "#F5F5F5",
            "link": "#0000EE"  # 链接蓝色
        }

        self.fonts = {
            "title": ("Arial", 16, "bold"),
            "subtitle": ("Arial", 11, "bold"),
            "normal": ("Arial", 10),
            "small": ("Arial", 9),
            "link": ("Arial", 9, "underline")
        }

        self.selected_insurance = tk.StringVar()
        self.input_fields = {}

        self.main_frame = tk.Frame(root, bg=self.colors["white"],
                                   highlightbackground=self.colors["border"],
                                   highlightthickness=1)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=2)

        #创建标题信息
        self.create_header()
        # 创建产品选择
        self.create_insurance_selector()
        # 创建动态字段区域
        self.input_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        self.input_frame.pack(fill=tk.BOTH, expand=True, pady=2)

        # 创建评估按钮
        self.button_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        self.button_frame.pack(fill=tk.X, pady=2)
        self.evaluate_btn = tk.Button(
            self.button_frame,
            text="评估保费",
            command=self.calculate_premium,
            bg=self.colors["primary_red"],
            fg=self.colors["white"],
            font=self.fonts["subtitle"],
            padx=15,
            pady=1,
            relief=tk.RAISED,
            bd=1
        )
        self.evaluate_btn.pack(side=tk.RIGHT)

        # 创建结果区域
        self.result_frame = tk.LabelFrame(
            self.main_frame,
            text="保费评估结果",
            bg=self.colors["white"],
            fg=self.colors["primary_red"],
            font=self.fonts["subtitle"],
            highlightbackground=self.colors["border"],
            highlightthickness=1,
            bd=0
        )
        self.result_frame.pack(fill=tk.BOTH, expand=True,padx=15, pady=15)

        self.result_text = scrolledtext.ScrolledText(
            self.result_frame,
            bg=self.colors["white"],
            font=self.fonts["normal"],
            wrap=tk.WORD,
            relief=tk.FLAT,
            highlightthickness=0,
            padx=15,
            pady=1
        )
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=1)
        self.result_text.insert(tk.END, "请选择保险类型并填写相关信息，然后点击'评估保费'按钮查看结果...")
        self.result_text.config(state=tk.DISABLED)

        self.update_input_fields()

    #实现方法
    def create_header(self):
        header_frame = tk.Frame(self.main_frame, bg=self.colors["white"])
        header_frame.pack(fill=tk.X)

        title_label = tk.Label(
            header_frame,
            text="保险保费评估",
            font=self.fonts["title"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        title_label.pack(side=tk.LEFT, padx=5, pady=1)

        #创建logo，Antinio.Chan（AC），可以通过图片方式（学习中）
        logo_frame = tk.Frame(header_frame, width=800, height=60, bg=self.colors["white"])
        logo_frame.pack(side=tk.RIGHT, padx=(1,0), pady=1)

        canvas = tk.Canvas(logo_frame, width=100, height=80, bg=self.colors["white"], highlightthickness=0)
        canvas.pack(fill=tk.BOTH, expand=True)

        center_x, center_y = 40, 30
        radius = 25

        points = []
        for i in range(6):
            angle_rad = math.pi / 3 * (i + 0.5)
            x = center_x + radius * math.cos(angle_rad)
            y = center_y + radius * math.sin(angle_rad)
            points.append(x)
            points.append(y)

        canvas.create_polygon(points, fill=self.colors["primary_red"], outline="", width=2)
        canvas.create_text(center_x, center_y, text="A.C", fill=self.colors["white"],
                           font=("Arial", 12, "bold"))

    def create_insurance_selector(self):
        selector_frame = tk.Frame(
            self.main_frame,
            bg=self.colors["light_red"],
            highlightbackground=self.colors["border"],
            highlightthickness=0.1
        )
        selector_frame.pack(fill=tk.X, pady=(0, 1), ipady=8)

        tk.Label(
            selector_frame,
            text="请选择保险类型:",
            font=self.fonts["normal"],
            bg=self.colors["light_red"],
            fg=self.colors["text"]
        ).pack(side=tk.LEFT, padx=15)

        insurance_types = ["人寿险", "健康险", "财产险", "车险"]
        self.selected_insurance.set(insurance_types[0])

        insurance_menu = ttk.Combobox(
            selector_frame,
            textvariable=self.selected_insurance,
            values=insurance_types,
            font=self.fonts["normal"],
            state="readonly",
            width=20
        )
        insurance_menu.pack(side=tk.LEFT, padx=10)
        insurance_menu.bind("<<ComboboxSelected>>", lambda event: self.update_input_fields())
        # 添加IFRS17链接
        """创建IFRS17链接区域"""
        # 创建链接框架
        link_frame = tk.Frame(selector_frame, bg=self.colors["white"])
        link_frame.pack(fill=tk.X, pady=(0, 10), anchor=tk.E)  # 靠右显示

        # 创建可点击的标签作为链接
        self.ifrs17_link = tk.Label(
            link_frame,
            text="想了解IFRS17？",
            font=self.fonts["link"],
            fg=self.colors["link"],
            bg=self.colors["white"],
            cursor="hand2"  # 鼠标悬停时显示手型光标
        )
        self.ifrs17_link.pack(side=tk.RIGHT, padx=5, pady=5)

        # 绑定点击事件
        self.ifrs17_link.bind("<Button-1>", self.open_ifrs17_link)

        # 绑定鼠标悬停效果
        self.ifrs17_link.bind("<Enter>", self.on_link_enter)
        self.ifrs17_link.bind("<Leave>", self.on_link_leave)

    def update_input_fields(self):
        for widget in self.input_frame.winfo_children():
            widget.destroy()

        self.input_fields.clear()
        insurance_type = self.selected_insurance.get()

        frame_title = tk.Label(
            self.input_frame,
            text=f"{insurance_type}信息填写",
            font=self.fonts["normal"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        frame_title.pack(anchor=tk.W, padx=10, pady=(0, 1))

        form_frame = tk.Frame(self.input_frame, bg=self.colors["white"])
        form_frame.pack(fill=tk.BOTH, expand=True, padx=10)

        if insurance_type == "人寿险":
            self.create_life_insurance_fields(form_frame)
        elif insurance_type == "健康险":
            self.create_health_insurance_fields(form_frame)
        elif insurance_type == "财产险":
            self.create_property_insurance_fields(form_frame)
        elif insurance_type == "车险":
            self.create_car_insurance_fields(form_frame)

        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, "请填写相关信息，然后点击'评估保费'按钮查看结果...")
        self.result_text.config(state=tk.DISABLED)

    def open_ifrs17_link(self, event):
        ifrs17_url = "https://www.ifrs.org/issued-standards/list-of-standards/ifrs-17-insurance-contracts/"
        webbrowser.open_new(ifrs17_url)

    def on_link_enter(self, event):
        """鼠标悬停在链接上时的效果"""
        self.ifrs17_link.config(fg=self.colors["secondary_red"])

    def on_link_leave(self, event):
        """鼠标离开链接时的效果"""
        self.ifrs17_link.config(fg=self.colors["link"])

    def create_life_insurance_fields(self, parent):
        fields = [
            {"label": "年龄:", "type": "entry", "name": "age", "validation": "number", "required": True},
            {"label": "保险金额(万元):", "type": "entry", "name": "amount", "validation": "number", "required": True},
            {"label": "性别:", "type": "option", "name": "gender", "options": ["男", "女"], "required": True},
            {"label": "职业:", "type": "option", "name": "occupation",
             "options": ["办公室职员", "销售", "体力劳动者", "高空作业", "危险行业"], "required": True},
            {"label": "保险期限(年):", "type": "option", "name": "term",
             "options": ["10", "20", "30", "至60岁", "至70岁", "终身"], "required": True},
            {"label": "是否吸烟:", "type": "option", "name": "smoker", "options": ["是", "否"], "required": True},
            {"label": "健康状况:", "type": "option", "name": "health",
             "options": ["优秀", "良好", "一般", "较差", "有既往病史"], "required": True}
        ]

        # 指定每行显示2个字段
        self._create_input_form(parent, fields, fields_per_row=2)

    def create_property_insurance_fields(self, parent):
        """创建财产险输入字段，示例：每行显示2-3个字段"""
        fields = [
            {"label": "财产类型:", "type": "option", "name": "property_type",
             "options": ["住宅", "商铺", "办公楼", "厂房", "其他"], "required": True},
            {"label": "财产估值(万元):", "type": "entry", "name": "value", "validation": "number", "required": True},
            {"label": "所在地区:", "type": "option", "name": "location",
             "options": ["一线城市", "二线城市", "三线城市", "四线及以下城市", "农村地区"], "required": True},
            {"label": "建筑年代:", "type": "option", "name": "construction_year",
             "options": ["5年以内", "5-10年", "10-20年", "20年以上"], "required": True},
            {"label": "保障范围:", "type": "multiple", "name": "coverage",
             "options": ["火灾", "水灾", "盗窃", "第三方责任"], "required": True}
        ]

        # 财产险特殊布局：前4个字段分2行（每行2个），最后一个字段单独一行
        self._create_input_form(parent, fields, fields_per_row=2)

    # 保持其他保险类型字段创建方法不变...
    def create_health_insurance_fields(self, parent):
        fields = [
            {"label": "年龄:", "type": "entry", "name": "age", "validation": "number", "required": True},
            {"label": "保险金额(万元):", "type": "entry", "name": "amount", "validation": "number", "required": True},
            {"label": "性别:", "type": "option", "name": "gender", "options": ["男", "女"], "required": True},
            {"label": "职业:", "type": "option", "name": "occupation",
             "options": ["办公室职员", "销售", "体力劳动者", "高空作业", "危险行业"], "required": True},
            {"label": "既往病史:", "type": "option", "name": "medical_history",
             "options": ["无", "轻微疾病", "慢性疾病", "重大疾病史"], "required": True},
            {"label": "是否有社保:", "type": "option", "name": "social_security",
             "options": ["有", "无"], "required": True},
            {"label": "保障范围:", "type": "multiple", "name": "coverage",
             "options": ["住院医疗", "门诊医疗", "重大疾病", "意外伤害"], "required": True},
        ]

        self._create_input_form(parent, fields, fields_per_row=2)

    def create_car_insurance_fields(self, parent):
        fields = [
            {"label": "车辆类型:", "type": "option", "name": "car_type",
             "options": ["小型轿车", "SUV", "面包车", "货车", "豪华车"], "required": True},
            {"label": "购置价格(万元):", "type": "entry", "name": "price", "validation": "number", "required": True},
            {"label": "使用年限(年):", "type": "entry", "name": "car_age", "validation": "number", "required": True},
            {"label": "车辆用途:", "type": "option", "name": "usage",
             "options": ["私家车", "公务车", "营运车辆"], "required": True},
            {"label": "车主年龄:", "type": "entry", "name": "owner_age", "validation": "number", "required": True},
            {"label": "驾驶年限(年):", "type": "entry", "name": "driving_years", "validation": "number",
             "required": True},
            {"label": "近3年理赔次数:", "type": "option", "name": "claims",
             "options": ["0次", "1次", "2次", "3次及以上"], "required": True}
        ]

        # 车险使用3字段每行的布局
        self._create_input_form(parent, fields, fields_per_row=3)

    def _create_input_form(self, parent, fields, fields_per_row=2):
        """通用方法创建输入表单，支持每行显示多个字段

        参数:
            parent: 父容器
            fields: 字段列表
            fields_per_row: 每行显示的字段数量，默认为2
        """
        # 清除父容器中所有现有组件
        for widget in parent.winfo_children():
            widget.destroy()

        # 配置列权重，使每个字段区域能够平均分配空间
        for col in range(fields_per_row):
            parent.columnconfigure(col, weight=1)

        # 遍历所有字段，按指定的每行数量进行布局
        for i, field in enumerate(fields):
            # 计算当前字段所在的行和列
            row = i // fields_per_row
            col = i % fields_per_row

            # 创建字段容器，包含标签和输入控件
            field_frame = tk.Frame(parent, bg=self.colors["white"])
            field_frame.grid(row=row, column=col, padx=5, pady=2, sticky=tk.W + tk.E)

            # 创建标签
            label_text = field["label"]
            if field.get("required", False):
                label_text += " *"

            tk.Label(
                field_frame,
                text=label_text,
                font=self.fonts["small"],
                bg=self.colors["white"],
                fg=self.colors["text"],
                anchor=tk.W,
                wraplength=150
            ).pack(anchor=tk.W, pady=(0, 2))

            # 根据字段类型创建不同的输入控件
            if field["type"] == "entry":
                entry = tk.Entry(
                    field_frame,
                    font=self.fonts["small"],
                    width=25,
                    highlightbackground=self.colors["border"],
                    highlightthickness=1
                )
                entry.pack(fill=tk.X)
                self.input_fields[field["name"]] = {
                    "widget": entry,
                    "type": "entry",
                    "required": field.get("required", False)
                }

                if field.get("validation") == "number":
                    validate_cmd = (self.root.register(self.validate_number), '%P')
                    entry.config(validate="key", validatecommand=validate_cmd)

            elif field["type"] == "option":
                var = tk.StringVar()
                var.set(field["options"][0])
                option_menu = tk.OptionMenu(field_frame, var, *field["options"])
                option_menu.config(
                    font=self.fonts["small"],
                    width=25,
                    bg=self.colors["white"],
                    activebackground=self.colors["light_red"],
                    highlightbackground=self.colors["border"],
                    highlightthickness=1
                )
                option_menu.pack(fill=tk.X)
                self.input_fields[field["name"]] = {
                    "widget": var,
                    "type": "option",
                    "required": field.get("required", False)
                }

            elif field["type"] == "multiple":
                frame_check = tk.Frame(field_frame, bg=self.colors["white"])
                frame_check.pack(fill=tk.X)

                vars_check = []
                for j, option in enumerate(field["options"]):
                    var = tk.BooleanVar()
                    chk = tk.Checkbutton(
                        frame_check,
                        text=option,
                        variable=var,
                        bg=self.colors["white"],
                        fg=self.colors["text"],
                        font=self.fonts["small"],
                        selectcolor=self.colors["primary_red"],
                        highlightbackground=self.colors["border"],
                        highlightthickness=1
                    )
                    chk.grid(row=j // 5, column=j % 5, sticky=tk.W, padx=3, pady=1)
                    vars_check.append((option, var))

                self.input_fields[field["name"]] = {
                    "widget": vars_check,
                    "type": "multiple",
                    "required": field.get("required", False)
                }

        # 添加必填项说明
        required_note = tk.Label(
            parent,
            text="* 为必填项",
            font=self.fonts["small"],
            bg=self.colors["white"],
            fg=self.colors["primary_red"]
        )
        required_note.grid(row=(len(fields) - 1) // fields_per_row + 1, column=0,
                           columnspan=fields_per_row, sticky=tk.W, padx=10, pady=1)

    # 验证数值
    def validate_number(self, value):
        if value == "":
            return True
        try:
            float(value)
            return True
        except ValueError:
            return False

    def get_input_values(self):
        values = {}
        for name, field_info in self.input_fields.items():
            widget = field_info["widget"]
            field_type = field_info["type"]

            if field_type == "entry":
                value = widget.get().strip()
                if value:
                    try:
                        values[name] = float(value)
                    except ValueError:
                        values[name] = value
                else:
                    values[name] = None

            elif field_type == "option":
                values[name] = widget.get()

            elif field_type == "multiple":
                selected = [option for option, var in widget if var.get()]
                values[name] = selected

        return values

    def validate_inputs(self, values):
        for name, field_info in self.input_fields.items():
            if field_info["required"]:
                value = values.get(name)

                if value is None or value == "":
                    field_name = self._get_field_display_name(name)
                    messagebox.showerror("输入错误", f"请填写完整信息: {field_name}")
                    return False

                if field_info["type"] == "multiple" and not value:
                    field_name = self._get_field_display_name(name)
                    messagebox.showerror("输入错误", f"请至少选择一项: {field_name}")
                    return False

        if "age" in values and values["age"] is not None:
            if values["age"] < 0 or values["age"] > 120:
                messagebox.showerror("输入错误", "年龄必须在0-120之间")
                return False

        if "car_age" in values and values["car_age"] is not None:
            if values["car_age"] < 0 or values["car_age"] > 50:
                messagebox.showerror("输入错误", "车辆使用年限必须在0-50之间")
                return False

        if "driving_years" in values and values["driving_years"] is not None:
            if values["driving_years"] < 0 or values["driving_years"] > 70:
                messagebox.showerror("输入错误", "驾驶年限必须在0-70之间")
                return False

        for field in ["amount", "value", "price"]:
            if field in values and values[field] is not None and values[field] <= 0:
                field_name = self._get_field_display_name(field)
                messagebox.showerror("输入错误", f"{field_name}必须大于0")
                return False

        return True

    def _get_field_display_name(self, field_name):
        field_map = {
            "age": "年龄",
            "gender": "性别",
            "occupation": "职业",
            "amount": "保险金额",
            "term": "保险期限",
            "smoker": "是否吸烟",
            "health": "健康状况",
            "coverage": "保障范围",
            "medical_history": "既往病史",
            "social_security": "是否有社保",
            "property_type": "财产类型",
            "value": "财产估值",
            "location": "所在地区",
            "construction_year": "建筑年代",
            "car_type": "车辆类型",
            "price": "购置价格",
            "car_age": "使用年限",
            "usage": "车辆用途",
            "owner_age": "车主年龄",
            "driving_years": "驾驶年限",
            "claims": "近3年理赔次数"
        }
        return field_map.get(field_name, field_name)

    def calculate_premium(self):
        input_values = self.get_input_values()

        if not self.validate_inputs(input_values):
            return

        insurance_type = self.selected_insurance.get()
        premium = 0
        details = []
        suggestions = []

        if insurance_type == "人寿险":
            premium, details, suggestions = self.calculate_life_premium(input_values)
        elif insurance_type == "健康险":
            premium, details, suggestions = self.calculate_health_premium(input_values)
        elif insurance_type == "财产险":
            premium, details, suggestions = self.calculate_property_premium(input_values)
        elif insurance_type == "车险":
            premium, details, suggestions = self.calculate_car_premium(input_values)

        self.display_result(insurance_type, premium, details, suggestions)

    def calculate_life_premium(self, values):
        details = []
        base_premium = values["amount"] * 10000 * 0.001
        details.append(f"基础保费: {base_premium:.2f}元 (保险金额的0.1%)")

        age_factor = 1.0
        if values["age"] <= 30:
            age_factor = 0.8
        elif values["age"] <= 50:
            age_factor = 1.0
        elif values["age"] <= 60:
            age_factor = 1.5
        else:
            age_factor = 2.0
        details.append(f"年龄系数: {age_factor}x (年龄: {values['age']}岁)")

        gender_factor = 1.0
        if values["gender"] == "男":
            gender_factor = 1.1
        details.append(f"性别系数: {gender_factor}x (性别: {values['gender']})")

        occupation_factors = {
            "办公室职员": 0.9,
            "销售": 1.0,
            "体力劳动者": 1.2,
            "高空作业": 1.8,
            "危险行业": 2.5
        }
        occupation_factor = occupation_factors[values["occupation"]]
        details.append(f"职业系数: {occupation_factor}x (职业: {values['occupation']})")

        smoker_factor = 1.0
        if values["smoker"] == "是":
            smoker_factor = 1.5
        details.append(f"吸烟系数: {smoker_factor}x (是否吸烟: {values['smoker']})")

        health_factors = {
            "优秀": 0.8,
            "良好": 1.0,
            "一般": 1.2,
            "较差": 1.8,
            "有既往病史": 2.5
        }
        health_factor = health_factors[values["health"]]
        details.append(f"健康系数: {health_factor}x (健康状况: {values['health']})")

        term_factor = 1.0
        if values["term"] == "10":
            term_factor = 1.2
        elif values["term"] == "20":
            term_factor = 1.0
        elif values["term"] == "30":
            term_factor = 0.9
        elif values["term"] == "至60岁":
            term_factor = 0.8
        elif values["term"] == "至70岁":
            term_factor = 0.9
        elif values["term"] == "终身":
            term_factor = 1.5
        details.append(f"期限系数: {term_factor}x (保险期限: {values['term']}年)")

        total_factor = age_factor * gender_factor * occupation_factor * smoker_factor * health_factor * term_factor
        total_premium = base_premium * total_factor

        details.append(f"\n总系数: {total_factor:.2f}x")
        details.append(f"年度保费评估: {total_premium:.2f}元")

        suggestions = [
            "1. 少吸烟少喝酒，活得更长久。",
            "2. 多吃青菜多运动，钱要花在刀刃上"
        ]

        return total_premium, details, suggestions

    def calculate_health_premium(self, values):
        details = []
        base_premium = values["amount"] * 10000 * 0.003
        details.append(f"基础保费: {base_premium:.2f}元 (保险金额的0.3%)")

        age_factor = 1.0
        if values["age"] <= 20:
            age_factor = 0.7
        elif values["age"] <= 40:
            age_factor = 1.0
        elif values["age"] <= 60:
            age_factor = 1.8
        else:
            age_factor = 2.5
        details.append(f"年龄系数: {age_factor}x (年龄: {values['age']}岁)")

        gender_factor = 1.0
        if values["gender"] == "女":
            gender_factor = 0.9
        details.append(f"性别系数: {gender_factor}x (性别: {values['gender']})")

        occupation_factors = {
            "办公室职员": 0.9,
            "销售": 1.0,
            "体力劳动者": 1.3,
            "高空作业": 1.9,
            "危险行业": 2.6
        }
        occupation_factor = occupation_factors[values["occupation"]]
        details.append(f"职业系数: {occupation_factor}x (职业: {values['occupation']})")

        coverage_factor = 1.0 + 0.2 * len(values["coverage"])
        details.append(f"保障范围系数: {coverage_factor}x (选择了{len(values['coverage'])}项保障)")

        history_factors = {
            "无": 0.9,
            "轻微疾病": 1.3,
            "慢性疾病": 2.0,
            "重大疾病史": 3.0
        }
        history_factor = history_factors[values["medical_history"]]
        details.append(f"健康状况系数: {history_factor}x (既往病史: {values['medical_history']})")

        social_factor = 1.0
        if values["social_security"] == "有":
            social_factor = 0.7
        details.append(f"社保系数: {social_factor}x (是否有社保: {values['social_security']})")

        total_factor = age_factor * gender_factor * occupation_factor * coverage_factor * history_factor * social_factor
        total_premium = base_premium * total_factor

        details.append(f"\n总系数: {total_factor:.2f}x")
        details.append(f"年度保费评估: {total_premium:.2f}元")

        suggestions = [
            "1. 有钱就买点，不然当我没说。",
            "2. 。。。。",
        ]

        return total_premium, details, suggestions

    def calculate_property_premium(self, values):
        details = []
        base_premium = values["value"] * 10000 * 0.0005
        details.append(f"基础保费: {base_premium:.2f}元 (财产估值的0.05%)")

        type_factors = {
            "住宅": 1.0,
            "商铺": 1.3,
            "办公楼": 1.2,
            "厂房": 1.8,
            "其他": 1.5
        }
        type_factor = type_factors[values["property_type"]]
        details.append(f"财产类型系数: {type_factor}x (类型: {values['property_type']})")

        location_factors = {
            "一线城市": 1.2,
            "二线城市": 1.0,
            "三线城市": 0.9,
            "四线及以下城市": 0.8,
            "农村地区": 1.1
        }
        location_factor = location_factors[values["location"]]
        details.append(f"地区系数: {location_factor}x (地区: {values['location']})")

        year_factors = {
            "5年以内": 0.8,
            "5-10年": 1.0,
            "10-20年": 1.3,
            "20年以上": 1.8
        }
        year_factor = year_factors[values["construction_year"]]
        details.append(f"建筑年代系数: {year_factor}x (年代: {values['construction_year']})")

        coverage_factor = 1.0 + 0.15 * len(values["coverage"])
        details.append(f"保障范围系数: {coverage_factor}x (选择了{len(values['coverage'])}项保障)")

        total_factor = type_factor * location_factor * year_factor * coverage_factor
        total_premium = base_premium * total_factor

        details.append(f"\n总系数: {total_factor:.2f}x")
        details.append(f"年度保费评估: {total_premium:.2f}元")

        suggestions = [
            "1. 这个真不建议要,除非你是大老板"
        ]

        return total_premium, details, suggestions

    def calculate_car_premium(self, values):
        details = []
        base_premium = values["price"] * 10000 * 0.01
        details.append(f"基础保费: {base_premium:.2f}元 (购置价格的1%)")

        type_factors = {
            "小型轿车": 1.0,
            "SUV": 1.1,
            "面包车": 1.2,
            "货车": 1.5,
            "豪华车": 1.8
        }
        type_factor = type_factors[values["car_type"]]
        details.append(f"车辆类型系数: {type_factor}x (类型: {values['car_type']})")

        car_age = values["car_age"]
        age_factor = 1.0
        if car_age <= 1:
            age_factor = 1.2
        elif car_age <= 3:
            age_factor = 1.0
        elif car_age <= 5:
            age_factor = 0.9
        elif car_age <= 10:
            age_factor = 1.1
        else:
            age_factor = 1.5
        details.append(f"车龄系数: {age_factor}x (车龄: {car_age}年)")

        usage_factors = {
            "私家车": 1.0,
            "公务车": 1.1,
            "营运车辆": 2.0
        }
        usage_factor = usage_factors[values["usage"]]
        details.append(f"用途系数: {usage_factor}x (用途: {values['usage']})")

        owner_age = values["owner_age"]
        owner_factor = 1.0
        if owner_age < 25:
            owner_factor = 1.5
        elif owner_age <= 60:
            owner_factor = 1.0
        else:
            owner_factor = 1.3
        details.append(f"车主年龄系数: {owner_factor}x (年龄: {owner_age}岁)")

        driving_years = values["driving_years"]
        driving_factor = 1.0
        if driving_years < 1:
            driving_factor = 1.8
        elif driving_years <= 3:
            driving_factor = 1.3
        elif driving_years <= 10:
            driving_factor = 1.0
        else:
            driving_factor = 0.8
        details.append(f"驾驶经验系数: {driving_factor}x (驾龄: {driving_years}年)")

        claims_factors = {
            "0次": 0.8,
            "1次": 1.0,
            "2次": 1.5,
            "3次及以上": 2.5
        }
        claims_factor = claims_factors[values["claims"]]
        details.append(f"理赔记录系数: {claims_factor}x (近3年: {values['claims']})")

        total_factor = type_factor * age_factor * usage_factor * owner_factor * driving_factor * claims_factor
        total_premium = base_premium * total_factor

        details.append(f"\n总系数: {total_factor:.2f}x")
        details.append(f"年度保费评估: {total_premium:.2f}元")

        suggestions = [
            "1. 有车必备，我家最便宜"
        ]

        return total_premium, details, suggestions

    def display_result(self, insurance_type, premium, details, suggestions):
        result_text = f"【{insurance_type}保费评估结果】\n\n"
        result_text += "\n".join(details)

        result_text += "\n\n【专业建议】\n"
        result_text += "\n".join(suggestions)

        result_text += "\n\n注：以上保费评估仅供参考，实际保费可能因具体条款和核保结果而有所不同。"
        result_text += "\n如需详细咨询，请联系智能客服(也就是百度AI)。"

        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, result_text)
        self.result_text.config(state=tk.DISABLED)


if __name__ == "__main__":
    root = tk.Tk()
    app = InsuranceCalculator(root)
    root.mainloop()
